package com.chen.config;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.util.HashMap;

/**
 * 对验证失败返回JSON数据的处理
 */
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //获取异常信息
        String localizedMessage = exception.getLocalizedMessage();
        response.setContentType("application/json;charset=UTF-8");
        HashMap<Object, Object> result= new HashMap<>();
        result.put("message", "验证失败");
        result.put("data", localizedMessage);
        result.put("code", 201);
        response.getWriter().write(JSON.toJSONString(result));


    }
}
